// 行政区域管理器
import type { DistrictData, DistrictStyle, DistrictConfig } from './types'
import { createPolygon, clearOverlays, formatDistrictData } from './utils'

/**
 * 行政区域管理器类
 */
export class DistrictManager {
  private map: any
  private districtSearch: any
  private polygons: any[] = []
  private currentLevel: 'country' | 'province' | 'city' | 'district' = 'province'
  private districtCache: Map<string, DistrictData> = new Map()
  private styleConfig: {
    province: DistrictStyle
    city: DistrictStyle
    district: DistrictStyle
  }

  constructor(map: any, districtSearch: any) {
    this.map = map
    this.districtSearch = districtSearch
    
    // 默认样式配置
    this.styleConfig = {
      province: {
        strokeColor: '#0078ff',
        strokeWeight: 3,
        strokeOpacity: 1,
        fillColor: '#0078ff',
        fillOpacity: 0.2,
        strokeStyle: 'solid'
      },
      city: {
        strokeColor: '#52c41a',
        strokeWeight: 2,
        strokeOpacity: 1,
        fillColor: '#52c41a',
        fillOpacity: 0.15,
        strokeStyle: 'solid'
      },
      district: {
        strokeColor: '#fa8c16',
        strokeWeight: 1,
        strokeOpacity: 1,
        fillColor: '#fa8c16',
        fillOpacity: 0.1,
        strokeStyle: 'solid'
      }
    }
  }

  /**
   * 设置样式配置
   */
  setStyleConfig(config: Partial<typeof this.styleConfig>) {
    this.styleConfig = { ...this.styleConfig, ...config }
  }

  /**
   * 搜索行政区域
   */
  async searchDistrict(
    keyword: string, 
    level: 'country' | 'province' | 'city' | 'district' = 'province',
    subdistrict: number = 1
  ): Promise<DistrictData | null> {
    return new Promise((resolve, reject) => {
      // 检查缓存
      const cacheKey = `${keyword}_${level}_${subdistrict}`
      if (this.districtCache.has(cacheKey)) {
        resolve(this.districtCache.get(cacheKey)!)
        return
      }

      // 配置搜索参数
      this.districtSearch.setLevel(level)
      this.districtSearch.setSubdistrict(subdistrict)
      this.districtSearch.setExtensions('all')

      this.districtSearch.search(keyword, (status: string, result: any) => {
        if (status === 'complete' && result.districtList && result.districtList.length > 0) {
          const district = formatDistrictData(result.districtList[0])
          
          // 缓存结果
          this.districtCache.set(cacheKey, district)
          resolve(district)
        } else {
          reject(new Error(`未找到行政区: ${keyword}`))
        }
      })
    })
  }

  /**
   * 显示省级行政区域
   */
  async showProvinces(country: string = '中国'): Promise<DistrictData[]> {
    try {
      const countryData = await this.searchDistrict(country, 'country', 1)
      if (!countryData || !countryData.children) {
        throw new Error('无法获取省级数据')
      }

      const provinces: DistrictData[] = []
      
      for (const province of countryData.children) {
        try {
          const provinceData = await this.searchDistrict(province.name, 'province', 0)
          if (provinceData && provinceData.boundaries) {
            provinces.push(provinceData)
            this.drawDistrictBoundaries(provinceData, 'province')
          }
        } catch (error) {
          console.warn(`加载省份失败: ${province.name}`, error)
        }
      }

      this.currentLevel = 'province'
      return provinces
    } catch (error) {
      console.error('显示省级区域失败:', error)
      throw error
    }
  }

  /**
   * 显示市级行政区域
   */
  async showCities(provinceName: string): Promise<DistrictData[]> {
    try {
      const provinceData = await this.searchDistrict(provinceName, 'province', 1)
      if (!provinceData || !provinceData.children) {
        throw new Error('无法获取市级数据')
      }

      const cities: DistrictData[] = []
      
      for (const city of provinceData.children) {
        try {
          const cityData = await this.searchDistrict(city.name, 'city', 0)
          if (cityData && cityData.boundaries) {
            cities.push(cityData)
            this.drawDistrictBoundaries(cityData, 'city')
          }
        } catch (error) {
          console.warn(`加载城市失败: ${city.name}`, error)
        }
      }

      this.currentLevel = 'city'
      return cities
    } catch (error) {
      console.error('显示市级区域失败:', error)
      throw error
    }
  }

  /**
   * 显示区县级行政区域
   */
  async showDistricts(cityName: string): Promise<DistrictData[]> {
    try {
      const cityData = await this.searchDistrict(cityName, 'city', 1)
      if (!cityData || !cityData.children) {
        throw new Error('无法获取区县数据')
      }

      const districts: DistrictData[] = []
      
      for (const district of cityData.children) {
        try {
          const districtData = await this.searchDistrict(district.name, 'district', 0)
          if (districtData && districtData.boundaries) {
            districts.push(districtData)
            this.drawDistrictBoundaries(districtData, 'district')
          }
        } catch (error) {
          console.warn(`加载区县失败: ${district.name}`, error)
        }
      }

      this.currentLevel = 'district'
      return districts
    } catch (error) {
      console.error('显示区县级区域失败:', error)
      throw error
    }
  }

  /**
   * 绘制行政区域边界
   */
  private drawDistrictBoundaries(
    district: DistrictData, 
    level: 'province' | 'city' | 'district'
  ): any[] {
    if (!district.boundaries || district.boundaries.length === 0) {
      return []
    }

    const style = this.styleConfig[level]
    const polygons: any[] = []

    district.boundaries.forEach((boundary, index) => {
      const polygon = createPolygon(this.map, boundary, style)
      
      // 添加区域信息到多边形
      polygon.setExtData({
        district: district,
        level: level,
        boundaryIndex: index
      })

      // 绑定点击事件
      polygon.on('click', (e: any) => {
        this.onDistrictClick(district, level, e)
      })

      // 绑定鼠标悬停事件
      polygon.on('mouseover', (e: any) => {
        this.onDistrictHover(district, level, polygon, true)
      })

      polygon.on('mouseout', (e: any) => {
        this.onDistrictHover(district, level, polygon, false)
      })

      polygons.push(polygon)
      this.polygons.push(polygon)
    })

    return polygons
  }

  /**
   * 区域点击事件处理
   */
  private onDistrictClick(
    district: DistrictData, 
    level: 'province' | 'city' | 'district',
    event: any
  ) {
    console.log(`点击${level}:`, district.name)
    
    // 根据当前级别决定下一步操作
    if (level === 'province' && this.currentLevel === 'province') {
      // 点击省份，显示该省的城市
      this.clearPolygons()
      this.showCities(district.name)
    } else if (level === 'city' && this.currentLevel === 'city') {
      // 点击城市，显示该市的区县
      this.clearPolygons()
      this.showDistricts(district.name)
    }

    // 触发自定义事件
    this.map.emit('district-click', {
      district,
      level,
      event
    })
  }

  /**
   * 区域悬停事件处理
   */
  private onDistrictHover(
    district: DistrictData,
    level: 'province' | 'city' | 'district',
    polygon: any,
    isHover: boolean
  ) {
    if (isHover) {
      // 悬停时高亮
      const hoverStyle = {
        ...this.styleConfig[level],
        strokeWeight: (this.styleConfig[level].strokeWeight || 1) + 1,
        fillOpacity: (this.styleConfig[level].fillOpacity || 0.2) + 0.1
      }
      polygon.setOptions(hoverStyle)
      
      // 显示信息窗口
      this.showInfoWindow(district, polygon)
    } else {
      // 恢复原样式
      polygon.setOptions(this.styleConfig[level])
      
      // 隐藏信息窗口
      this.hideInfoWindow()
    }
  }

  /**
   * 显示信息窗口
   */
  private showInfoWindow(district: DistrictData, polygon: any) {
    if (!window.AMap) return

    const content = `
      <div style="padding: 8px; font-size: 12px;">
        <div style="font-weight: bold; margin-bottom: 4px;">${district.name}</div>
        <div>代码: ${district.adcode}</div>
        <div>级别: ${district.level}</div>
      </div>
    `

    const infoWindow = new window.AMap.InfoWindow({
      content: content,
      offset: new window.AMap.Pixel(0, -10)
    })

    // 获取多边形中心点
    const bounds = polygon.getBounds()
    const center = bounds.getCenter()
    
    infoWindow.open(this.map, center)
    
    // 保存引用以便后续关闭
    this.currentInfoWindow = infoWindow
  }

  private currentInfoWindow: any = null

  /**
   * 隐藏信息窗口
   */
  private hideInfoWindow() {
    if (this.currentInfoWindow) {
      this.currentInfoWindow.close()
      this.currentInfoWindow = null
    }
  }

  /**
   * 显示指定区域
   */
  async showSpecificDistrict(
    keyword: string,
    level: 'province' | 'city' | 'district' = 'city'
  ): Promise<DistrictData | null> {
    try {
      this.clearPolygons()
      
      const district = await this.searchDistrict(keyword, level, 0)
      if (district) {
        this.drawDistrictBoundaries(district, level)
        
        // 调整地图视野
        if (this.polygons.length > 0) {
          this.map.setFitView(this.polygons)
        }
        
        this.currentLevel = level
        return district
      }
      
      return null
    } catch (error) {
      console.error('显示指定区域失败:', error)
      throw error
    }
  }

  /**
   * 返回上一级
   */
  async goBack(): Promise<void> {
    this.clearPolygons()
    
    switch (this.currentLevel) {
      case 'district':
        // 从区县返回到省级
        await this.showProvinces()
        break
      case 'city':
        // 从城市返回到省级
        await this.showProvinces()
        break
      case 'province':
        // 已经是最高级别
        break
    }
  }

  /**
   * 清除所有多边形
   */
  clearPolygons(): void {
    clearOverlays(this.map, this.polygons)
    this.hideInfoWindow()
  }

  /**
   * 获取当前级别
   */
  getCurrentLevel(): 'country' | 'province' | 'city' | 'district' {
    return this.currentLevel
  }

  /**
   * 获取缓存的区域数据
   */
  getCachedDistricts(): DistrictData[] {
    return Array.from(this.districtCache.values())
  }

  /**
   * 清除缓存
   */
  clearCache(): void {
    this.districtCache.clear()
  }

  /**
   * 销毁管理器
   */
  destroy(): void {
    this.clearPolygons()
    this.clearCache()
    this.map = null
    this.districtSearch = null
  }
}